%%%-------------------------------------------------------------------
%%% @author root
%%% @copyright (C) 2016, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 14. 二月 2016 下午8:52
%%%-------------------------------------------------------------------
-module(cus_message_handler).
-behaviour(cowboy_http_handler).

-include("cus.hrl").

-export([init/3]).
-export([handle/2]).
-export([terminate/3]).




init(_Type, Req, _Opts) ->
  {ok, Req, undefined_state}.

handle(Req, State) ->
  {Method,_} = cowboy_req:method(Req),
  HasBody = cowboy_req:has_body(Req),
  {CookieVal, Req2} = cowboy_req:cookie(<<"sessionid">>, Req),
%%  check SessionID and refresh cookie
  case cus_util:filter(CookieVal) of
    {true,UserName, PassWord} ->
      SessionID = cus_util:get_session_id(UserName,PassWord),
      Req3 = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, [
        {max_age, ?COOKIE_TIME}
      ], Req2),
      {ok,Req4} = maybe_echo(Method, HasBody, Req3),
      {ok, Req4, State};
    _->
      {ok, Body} = login_dtl:render([
      ]),
      {ok,Req3} = echo(Body, Req2),
      {ok, Req3, State}
  end.

terminate(_Reason, _Req, _State) ->
  ok.

maybe_echo(<<"GET">>, false, Req) ->
  {Mid,Req2} = cowboy_req:qs_val(<<"mid">>,Req),
  {Cid,Req2} = cowboy_req:qs_val(<<"cid">>,Req),
  case Mid of
    undefined->
      {ok, Body} = cus_message_detail_dtl:render([
        {page, <<"0">>}
      ]),
      echo(Body, Req);
      _->
      Info = cus_redis:get_message(Mid),
      case Info of
        undefined->
          {ok, Body} = cus_message_detail_dtl:render([
          {page, <<"0">>},
          {mid, Mid}
          ]),
          echo(Body, Req2);
          _->
            {ok, Body} = cus_message_detail_plus_dtl:render([
            {cid, Cid},
            {page, <<"0">>},
            {mid, Info#msg.mid},
            {conversationid, Info#msg.conversationid},
            {conversationinfo, Info#msg.conversationinfo},
            {msgtype, Info#msg.msgtype},
            {fromuser,Info#msg.fromuser},
            {members,?l2b(Info#msg.members)},
            {content, Info#msg.content},
            {msgtime, cus_util:utc_to_datetime(?l2i(Info#msg.msgtime) div 1000)},
            {msgstatus, Info#msg.msgstatus}
            ]),
            echo(Body, Req2)
        end
   end;


maybe_echo(<<"POST">>, true, Req) ->
  {ok, PostVals, Req2} = cowboy_req:body_qs(Req),
  PageSize = ?PAGE_SIZE,
  Page = proplists:get_value(<<"page">>, PostVals),
  Cid = proplists:get_value(<<"cid">>, PostVals),
  Mid = proplists:get_value(<<"mid">>, PostVals),
  case ?b2l(Cid) of
    [] ->
      case ?b2l(Mid) of
          []->
            {ok, Body} = cus_message_detail_dtl:render([
              {page, <<"0">>}
            ]),
           echo(Body, Req2);
        _->
            Info = cus_redis:get_message(Mid),
            case Info of
            undefined->
              {ok, Body} = cus_message_detail_dtl:render([
                {page, <<"0">>},
                {mid,Mid}
              ]),
              echo(Body, Req2);
              _->
                {ok, Body} = cus_message_detail_plus_dtl:render([
                  {mid, Info#msg.mid},
                  {page, <<"0">>},
                  {conversationid, Info#msg.conversationid},
                  {conversationinfo, Info#msg.conversationinfo},
                  {msgtype, Info#msg.msgtype},
                  {fromuser,Info#msg.fromuser},
                  {members,?l2b(Info#msg.members)},
                  {content, Info#msg.content},
                  {msgtime, cus_util:utc_to_datetime(?l2i(Info#msg.msgtime) div 1000)},
                  {msgstatus, Info#msg.msgstatus}
                ]),
                echo(Body, Req2)
             end
       end;
    _->
      case ?b2l(Mid) of
        []->
          Match = lists:concat([?b2l(Cid),"_*"]),
          Mids = cus_redis:get_message_ids(Match),
          SeqMax = case [cus_util:getSeq(Mid1)||Mid1 <- Mids] of
                   []->
                     0;
                   _->
                     lists:max([cus_util:getSeq(Mid1)||Mid1 <- Mids])
                 end,

          TotalPages = case SeqMax rem PageSize of
                         0 ->
                           trunc(SeqMax/PageSize);
                         _->
                           trunc(SeqMax/PageSize)+1
                       end,
          PageCountList = lists:seq(1,TotalPages),
          PageCountList1 = lists:seq(1,4),
          BeforePage = binary_to_integer(Page) - 1,
          BeforePage2 = binary_to_integer(Page) - 2,
          AfterPage = binary_to_integer(Page) + 1,
          AfterPage2 = binary_to_integer(Page) + 2,
          AfterPage3 = binary_to_integer(Page) + 3,
          BeforeTotalPages = TotalPages - 1,
          BeforeTotalPages2 = TotalPages - 2,

          Data = case TotalPages of
                    0->
                      [];
                   _->
                     MidList= case AfterPage of
                            TotalPages->
                                  lists:seq(binary_to_integer(Page)*PageSize+1,SeqMax);
                                _->
                                  lists:seq(binary_to_integer(Page)*PageSize+1,(binary_to_integer(Page)+1)*PageSize)
                              end,
                     MsgRecord = [cus_redis:get_message(lists:concat([?b2l(Cid),"_",Mid1]))||Mid1<-MidList],
                      [[Record#msg.mid,
                       Record#msg.conversationid,
                       Record#msg.msgtype,
                       Record#msg.fromuser,
                       Record#msg.members,
                       Record#msg.content,
                       cus_util:utc_to_datetime(?l2i(Record#msg.msgtime) div 1000),
                       Record#msg.msgstatus]||Record <- MsgRecord]
                 end,

          {ok, Body} = cus_message_list_dtl:render([
            {cid, Cid},
            {page, Page},
            {beforePage, BeforePage},
            {beforePage2, BeforePage2},
            {afterPage, AfterPage},
            {afterPage2, AfterPage2},
            {afterPage3,AfterPage3},
            {beforeTotalPages, BeforeTotalPages},
            {beforeTotalPages2, BeforeTotalPages2},
            {totalPages,TotalPages},
            {pageCountList,PageCountList},
            {pageCountList1,PageCountList1},
            {data,Data}
          ]),
          echo(Body, Req2);
      _->
        Info = cus_redis:get_message(Mid),
        case Info of
          undefined->
            {ok, Body} = cus_message_detail_dtl:render([
              {page, <<"0">>},
              {mid, Mid}
            ]),
            echo(Body, Req2);
          _->
            {ok, Body} = cus_message_detail_plus_dtl:render([
              {cid, Cid},
              {page, <<"0">>},
              {mid, Info#msg.mid},
              {conversationid, Info#msg.conversationid},
              {conversationinfo, Info#msg.conversationinfo},
              {msgtype, Info#msg.msgtype},
              {fromuser,Info#msg.fromuser},
              {members,?l2b(Info#msg.members)},
              {content, Info#msg.content},
              {msgtime, cus_util:utc_to_datetime(?l2i(Info#msg.msgtime) div 1000)},
              {msgstatus, Info#msg.msgstatus}
            ]),
            echo(Body, Req2)
        end
      end
  end;



maybe_echo(<<"POST">>, false, Req) ->
  {ok, Body} = failed_dtl:render([
    {errorMsg,"Missing body"}
  ]),
  cowboy_req:reply(400, [{<<"content-type">>, <<"text/html; charset=utf-8">>}], Body, Req);
maybe_echo(_, _, Req) ->

  {ok, Body} = failed_dtl:render([
    {errorMsg,"405"}
  ]),
  cowboy_req:reply(405, [{<<"content-type">>, <<"text/html; charset=utf-8">>}], Body, Req).


echo(undefined, Req) ->
  {ok, Body} = failed_dtl:render([
    {errorMsg,"system error"}
  ]),
  cowboy_req:reply(400, [{<<"content-type">>, <<"text/html; charset=utf-8">>}], Body, Req);
echo(Body, Req) ->
  cowboy_req:reply(200, [
    {<<"content-type">>, <<"text/html; charset=utf-8">>}
  ], Body, Req).

